/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.bangcommunity.bbframe.sdm.web.shiro.realm;

import com.bangcommunity.bbframe.sdm.web.shiro.BaseSdmAuthenticationToken;
import com.bangcommunity.bbframe.sdm.web.shiro.ISdmWebTokenService;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

public class BaseSdmShiroRealm<PK extends Serializable, TK extends BaseSdmAuthenticationToken>
        extends AbstractSdmShiroRealm<PK, TK> implements InitializingBean {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired(required = false)
    protected ISdmWebTokenService<PK> sdmWebTokenService;

    @Override
    protected IShiroUser<PK> retriveFromToken(TK token) {
        if (null == token) {
            logger.error("no token when login");
            throw new AuthenticationException("登录信息有误");
        }

        BaseShiroUser ssoShiroUser = new BaseShiroUser();
        ssoShiroUser.setToken(token.getSsoToken());
        ssoShiroUser.setUid(readUidByToken(token.getSsoToken()));
        return ssoShiroUser;
    }

    protected PK readUidByToken(String token) {
        PK readUidByToken = sdmWebTokenService.readUidByToken(token);
        if (null == readUidByToken) {
            logger.error("read token fail when login");
            throw new AuthenticationException("登录信息有误");
        }
        return readUidByToken;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.setAuthenticationTokenClass(BaseSdmAuthenticationToken.class);
    }
}
